package com.hemerasolutions.v2trainer.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.hemerasolutions.v2trainer.dao.interfaces.UserDaoInterface;
import com.hemerasolutions.v2trainer.model.security.AccessRole;
import com.hemerasolutions.v2trainer.service.interfaces.BaseServiceInterface;


/**
 * @author ryegros
 * Authentication service for Web Application
 */
@Service("authUserService")
public class AuthUserService extends BaseService implements UserDetailsService, BaseServiceInterface {

	private static final long serialVersionUID = 1L;

	@Autowired
	UserDaoInterface userDao;

	@Override
	public UserDetails loadUserByUsername(String userName)	throws UsernameNotFoundException {

		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		boolean isNotExpired = false;
		boolean isActive  = false;

		try{
			com.hemerasolutions.v2trainer.model.users.User user = userDao.findByUserName(userName);
			if(user != null){

				if(user.getUserType() == com.hemerasolutions.v2trainer.model.users.User.USERTYPE_ADMIN){
					isActive = true;
					isNotExpired = true;
				}else{
					isActive = user.isActive();
					isNotExpired = !user.getExpireOn().before(new Date());
				}
					
				authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
				for(AccessRole role:user.getRoles()){
					authorities.add(new SimpleGrantedAuthority(role.getName()));
				}

				return new User(user.getEmail(), user.getPassword(), isActive, isNotExpired,isNotExpired,isActive, authorities);
			}
		}catch(Exception ex){
			throw new UsernameNotFoundException(this.localizedText("UserNotFound"));
		}
		throw new UsernameNotFoundException(this.localizedText("UserNotFound"));
	
	}
}
